<template>
	<input type="file" accept=".xls,.xlsx" class="upload-file" @change="changeExcel($event)" />
</template>

<script>
	import {
		ref
	} from 'vue'
	import * as XLSX from 'xlsx'
	import {
		ElMessage
	} from 'element-plus'
	
	export default {
		data() {
			return {
				methods: {
					getExcelData(data) {
						let obj = {};
						const list = [];
						data.forEach((item) => {
							obj = {};
							for (const key in item) {
								if (key === '学生姓名') {
									obj.userName = item[key];
								} else if (key === '学号') {
									obj.studentId = item[key];
								} else if (key === '密码') {
									obj.password = item[key];
								} else if (key === '性别') {
									obj.sex = item[key];
								} else if (key === '手机号') {
									obj.phone = item[key];
								}
								else if (key === '手机号') {
									obj.phone = item[key];
								}
							}
							list.push(obj);
						});
					 this.clockTable = list;
					},
					changeExcel(e) {
					
						const tableData = ref([]);
						const files = e.target.files
						if (files.length <= 0) {
							return false
						} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
							console.log('上传格式不正确，请上传xls或者xlsx格式');
							return false;
						}
						// 读取表格
						const fileReader = new FileReader()
						fileReader.onload = ev => {
							const workbook = XLSX.read(ev.target.result, {
								type: "binary"
							})
							const wsname = workbook.SheetNames[0]
							const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
							console.log('ws:', ws) // 转换成json的数据
							//  dealExcel(ws) ...对数据进行自己需要的操作 
							tableData.value = ws
							this.getExcelData(ws);
							const _self = this;
							this.$axios.post('http://localhost:8849/risk-troubleshoot/getdata', {
								jsonArray: _self.clockTable,
							}, {
								headers: {
									"Authorization": this.$cookies.get('token')
								}
							}).then(function(response) {
								console.log(response);
								if (response.data.code === 400) {
									ElMessage.success('Oops, this is a success message.');
								} else {
									ElMessage.error('Congrats, this is a error message.');
								}
							});
						}
						fileReader.readAsBinaryString(files[0])
					},
				}
			}
</script>

<style>
</style>